﻿using clf.weighing.entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace weighing
{

    public class InitConfigDao : BaseDao<InitConfig>
    {
        #region instance

        private static InitConfigDao? instance;
        public static InitConfigDao Instance => instance ??= new InitConfigDao();

        public override string GetTableName()
        {
            return "init_config";
        }
        #endregion



        /// <summary>
        /// 获取本地的初始化配制
        /// </summary>
        /// <returns></returns>
        public InitConfig GetInitConfig()
        {
            string condition = " id <= 10 ";
            String sql = SqlBuilder.GetSelectSql(GetTableName(), null, condition, null, null, null, 1, 0);
            var data = Sqlite.Select<InitConfig>(sql);
            var config = data.FirstOrDefault();
            config ??= GetDefault();
            return config;
        }

        private InitConfig GetDefault()
        {
            int mid = 1;        
            long clientId = IdHelper.LongID - 100000;
            var temp = clientId.ToString();
            var cNumber = "C-" + temp.Substring(6, temp.Length - 6);
            var initConfig = new InitConfig
            {
                clientId = 1,
                clientNumber = cNumber,
                machineId = mid,
                companyId = 0,
                companyName = string.Empty,
                scaleHouseId = 0,
            };

            int res = Sqlite.Insert<InitConfig>(initConfig);
            if(res > 0)
            {
                return initConfig;
            }else
            {
                throw new Exception("未能获取本地的初始化配制");
            }
            
        }

    }

}
